package com.aegean.thread.base;

import java.util.Random;

public class ThreadLocal {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		for (int i = 0; i < 2; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					int data = new Random().nextInt();
					System.out.println(Thread.currentThread().getName()
							+ " has put data :" + data);
					ThreadScopeData.getInstanceThread().setName("name" + data);
					ThreadScopeData.getInstanceThread().setValue(data);
					new A().get();
					new B().get();
					new C().get();
				}
			}).start();
		}

	}

	static class A {
		private ThreadScopeData threadData;

		public void get() {
			threadData = ThreadScopeData.getInstanceThread();
			System.out.println("A------线程：" + Thread.currentThread().getName()
					+ "  获取数据:" + threadData.getValue());
		}
	}

	static class B {
		private ThreadScopeData threadData;

		public  void get() {
			threadData = ThreadScopeData.getInstanceThread();
			System.out.println("B------线程：" + Thread.currentThread().getName()
					+ "  获取数据:" + threadData.getValue());
		}
	}
	static class C {
		private ThreadScopeData threadData;

		public  void get() {
			threadData = ThreadScopeData.getInstanceThread();
			System.out.println("C------线程：" + Thread.currentThread().getName()
					+ "  获取数据:" + threadData.getValue());
		}
	}

}

class ThreadScopeData {//共享数据实体类
	public static ThreadScopeData getInstanceThread() {
		ThreadScopeData instance = threadMap.get();
		if (instance == null) {
			instance = new ThreadScopeData();
			threadMap.set(instance);
		}
		return instance;
	}
	private static final java.lang.ThreadLocal<ThreadScopeData> threadMap = new java.lang.ThreadLocal<ThreadScopeData>();
	private String name;
	private int value;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}
}